import {Button, message, Modal, Radio, Tag} from 'antd';
import React, {useRef, useState} from 'react';
import {PageContainer} from '@ant-design/pro-layout';
import {isSuccess} from "@/utils/utils";
import {CourseManager} from "@/services/api-functions";
import ProTable, {ActionType, ProColumns} from "@ant-design/pro-table";
import {history} from "@@/core/history";
import {ExclamationCircleOutlined, PlusOutlined} from "@ant-design/icons";
import {SYS_ENUMS} from "@/utils/constants";

export const handleCoursePublishStatus = async (select: any, state: string) => {
  if (!select) return true;
  try {
    if (isSuccess((await CourseManager.courseOperate(select.id, state))?.code)) {
      message.success('PUBLISHED' === state ? '发布成功' : '取消发布成功');
      return true;
    }
    return false
  } catch (error) {
    return false;
  }
};

const CourseList: React.FC<any> = ({}) => {
  const actionRef = useRef<ActionType>();
  const columns: ProColumns[] = [
    {
      title: '封面',
      dataIndex: ['cover', 'url'],
      ellipsis: true,
      valueType: 'image',
      hideInSearch: true,
      width: 100,
      fixed: 'left'
    },
    {
      title: '课程标题',
      dataIndex: 'title',
      ellipsis: true,
      width: 170,
      render: (dom, record) => {
        return (
          <a onClick={()=>history.push(`/resource/detail/${record.id}`)}>
            {dom}
          </a>
        );
      },
    },
    {
      title: '课程老师',
      dataIndex: 'userName',
      ellipsis: true,
      hideInTable: true,
      width: 120,
    },
    {
      title: '课程老师',
      dataIndex: ['userDto', 'nickName'],
      ellipsis: true,
      hideInSearch: true,
      width: 120,
    },
    {
      title: '分类',
      dataIndex: 'difficulty',
      valueEnum: SYS_ENUMS.COURSE_DIFFICULTY,
      width: 100,
      hideInForm: true,
    },
    {
      title: '学员圈子',
      dataIndex: ['circle', 'title'],
      hideInSearch: true,
      width: 130,
    },
    {
      title: '课程状态',
      dataIndex: 'sellingState',
      valueEnum: SYS_ENUMS.SELLING_STATE,
      hideInSearch: true,
      width: 100,
      hideInForm: true,
    },
    {
      title: '付费类型',
      dataIndex: 'paymentType',
      valueEnum: SYS_ENUMS.RESOURCE_PAYMENT_TYPE,
      width: 100,
      hideInForm: true,
    },
    {
      title: '加入会员',
      dataIndex: 'membersFree',
      valueEnum: SYS_ENUMS.BOOLEAN_ENUMS,
      hideInSearch: true,
      width: 80,
    },
    {
      title: '售价',
      dataIndex: 'sellingPrice',
      width: 100,
      hideInSearch: true,
      hideInForm: true,
    },
    {
      title: '浏览量',
      dataIndex: 'browseNum',
      ellipsis: true,
      hideInSearch: true,
      width: 70,
    },
    {
      title: '订阅人数',
      dataIndex: 'tradingNum',
      ellipsis: true,
      hideInSearch: true,
      width: 80,
    },
    {
      title: '评价数',
      dataIndex: 'focusNum',
      ellipsis: true,
      hideInSearch: true,
      width: 70,
    },
    {
      title: '发布时间',
      dataIndex: 'gmtCreateTimeRange',
      valueType: 'dateTimeRange',
      width: 170,
      hideInTable: true,
    },
    {
      title: '发布时间',
      dataIndex: 'gmtCreate',
      ellipsis: true,
      hideInSearch: true,
      width: 150,
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      hideInSearch: true,
      hideInForm: true,
      fixed:'right',
      render: (_, record) => [
        <a key="edit" onClick={()=>history.push(`/course/edit/${record.id}`)}>编辑</a>,
        <a key="edit" href={`/course/detail/${record?.id}`}>详情</a>,
        record.sellingState === 'UP'
          ? <a key="edit" onClick={() => Modal.confirm({
            title: '提示',
            icon: <ExclamationCircleOutlined/>,
            content: <span>确定要下架 <Tag color='#108ee9'>{record.title}</Tag> 吗？</span>,
            okText: '下架',
            cancelText: '取消',
            onOk: async () => {
              if (await handleCoursePublishStatus(record, 'DOWN')) {
                actionRef.current?.reload()
              }
            },
          })}>下架</a>
          : <a key="edit" onClick={() => Modal.confirm({
            title: '提示',
            icon: <ExclamationCircleOutlined/>,
            content: <span>确定要上架 <Tag color='#108ee9'>{record.title}</Tag> 吗？</span>,
            okText: '上架',
            cancelText: '取消',
            onOk: async () => {
              if (await handleCoursePublishStatus(record, 'UP')) {
                actionRef.current?.reload()
              }
            },
          })}>上架</a>,
      ],
    },
  ];
  const [upState, setUpState] = useState<'ALL' | 'UP' | 'DOWN'>('ALL');
  const [countInfo, setCountInfo] = useState<{ ALL: number, UP: number, DOWN: number }>({
    ALL: 0,
    UP: 0,
    DOWN: 0,
  });

  return (
    <PageContainer>
      <ProTable<any, any>
        actionRef={actionRef}
        rowKey="key"
        search={{labelWidth: 120,}}
        headerTitle={<Radio.Group value={upState} onChange={(e) => {
          setUpState(e.target.value)
          actionRef.current?.reload()
        }}>
          <Radio.Button value='ALL'>全部 {countInfo?.ALL ?? 0}</Radio.Button>
          <Radio.Button value='UP'>已上架 {countInfo?.UP ?? 0}</Radio.Button>
          <Radio.Button value='DOWN'>已下架 {countInfo?.DOWN ?? 0}</Radio.Button>
        </Radio.Group>}
        toolBarRender={() => [
          <Button
            type="primary"
            key="primary"
            onClick={() => history.push('/course/edit')}>
            <PlusOutlined/> 新建
          </Button>
        ]}
        request={async (params) => {

          const query = {...params}
          if (upState !== 'ALL') {
            query.sellingState = upState
          }
          if (params.gmtCreateTimeRange) {
            query.startTime = params.gmtCreateTimeRange[0]
            query.endTime = params.gmtCreateTimeRange[1]
            delete query.gmtCreateTimeRange
          }

          const {data: {data, total}, code}: any = await CourseManager.list(query);

          const res = await CourseManager.countInfo();

          if(isSuccess(res.code)){
            setCountInfo(res.data)
          }

          return {data: data || [], success: isSuccess(code), total: isSuccess(code) ? total : 0};
        }}
        columns={columns}
        scroll={{ x: 1300 }}
      />
    </PageContainer>
  );
};

export default CourseList;
